﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Wams.Server
{
    public enum LogLevel
    {
        Debug,
        Info,
        Normal,
        Warning,
        Error,
        Critical
    }

    public class LogMessage : TableEntity
    {
        public string LevelStr { get; set; }
        private LogLevel _level = LogLevel.Normal;
        public LogLevel Level
        {
            get { return _level; }
            set { _level = value; LevelStr = value.ToString(); }
        }
        public string Message {get; set;}
    }

    public static class Logger
    {
        public static void Log(string message)
        { Log(LogLevel.Normal, message); }

        public static void Log(LogLevel level, string message)
        {
            try
            {
                LogMessage msg = new LogMessage() { Level = level, Message = message };
                msg.PartitionKey = RoleEnvironment.CurrentRoleInstance.Id;
                msg.RowKey = Guid.NewGuid().ToString();
                Log(msg);
            }
            catch { /* Logging should never throw exceptions! */ }
        }

        private static void Log(LogMessage msg)
        {
            CloudTableClient tableClient = WamsCore.MainStorageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(WamsCore.ContainerName + "log");
            table.CreateIfNotExists();

            TableOperation tOp = TableOperation.Insert(msg);
            table.Execute(tOp);
        }
    }
}